<template>
	<view class="content">
		<image class="logo" v-if="imageUrl" :src="imageUrl" mode="aspectFill"></image>
		<view class="btn-group">
			<button class="btn" @click="chooseImage">选择图片显示</button>
			<button class="btn" @click="previewImage">预览图片</button>
			<button class="btn" @click="getImageInfo">获取图片信息</button>
			<button class="btn" @click="downloadNetworkImage">下载网络图片</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imageUrl: "/static/logo.png",
				tempFilePath: ''
			}
		},
		methods: {
			chooseImage() {
				uni.chooseImage({
					count: 1, // 最多选择1张图片
					sizeType: ['original', 'compressed'], // 原图、压缩图均可
					sourceType: ['album', 'camera'], // 可从相册选或相机拍
					success: (res) => {
						// 选择成功，保存临时路径
						this.tempFilePath = res.tempFilePaths[0];
						this.imageUrl = res.tempFilePaths[0]; // 显示图片
					},
					fail: (err) => {
						console.log('选择图片失败：', err);
					}
				});
			},
			// 预览图片
			previewImage() {
				if (!this.tempFilePath) {
					uni.showToast({
						title: '请先选择图片',
						icon: 'none'
					});
					return;
				}
				uni.previewImage({
					urls: [this.tempFilePath], // 需要预览的图片地址数组
					current: this.tempFilePath // 当前显示的图片地址
				});
			},
			// 获取图片信息
			getImageInfo() {
				if (!this.tempFilePath) {
					uni.showToast({
						title: '请先选择图片',
						icon: 'none'
					});
					return;
				}
				uni.getImageInfo({
					src: this.tempFilePath,
					success: (info) => {
						console.log('图片信息：', info);
						uni.showModal({
							title: '图片信息',
							content: `宽度：${info.width}px\n高度：${info.height}px\n格式：${info.type}\n路径：${info.path}`,
							showCancel: false
						});
					},
					fail: (err) => {
						console.log('获取图片信息失败：', err);
					}
				});
			},
			downloadNetworkImage() {
				const imageUrl = "https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg";
				const imageTask = uni.downloadFile({
					url: imageUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							this.imageUrl = res.tempFilePath;
							this.tempFilePath = res.tempFilePath;
						} else {
							console.log("下载失败，状态码：", res.statusCode);
						}
					},
					fail: (err) => {
						console.log("下载网络图片失败：", err);
					}
				});
				// 监听下载进度
				imageTask.onProgressUpdate((res) => {
					console.log("下载进度:", res.progress + "%");
					console.log("已下载:", res.totalBytesWritten);
					console.log("总大小:", res.totalBytesExpectedToWrite);
				});
			}
		}
	};
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
		border-radius: 100rpx;
	}

	.btn-group {
		display: flex;
		flex-direction: column;
		gap: 10px;
	}

	.btn {
		width: 100%;
	}
</style>